// import createEventHub from "ynw/createEventHub";
import createEventHub from "./createEventHub";
const hub = createEventHub();
const REMOTE_DATA = "REMOTE_DATA";

// Web端调试不向客户端发送请求
const isWeb = /isWeb/.test(window.location.href);

const addPrefix = (codes) => {
  const prefixs = { 0: "sz.", 3: "sz.", 6: "sh." };
  return codes.map((item) => {
    const first = `${item}`.substring(0, 1);
    const pre = prefixs[first] || "block.";
    return pre + item;
  });
};


const formatNum = (num) =>{
  let unit = "",
      metricton = "";
  if (num < 0) {
    num = -num;
    metricton = "-";
  }
  switch (true) {
    case num >= 100000000:
      unit = (num / 100000000).toFixed(2) + "亿";
      break;
    case num < 100000000 && num >= 1000:
      unit = (num / 10000).toFixed(2) + "万";
      break;
    case num < 1000:
      unit = num;
      break;
  }
  return metricton + unit;
};


/*const formatNum = (num) => {
  let unit = "",
    metricton = "";
  if (num < 0) {
    num = -num;
    metricton = "-";
  }
  switch (true) {
    case num >= 100000000:
      unit = (num / 100000000).toFixed(2) + "亿";
      break;
    case num >= 10000000 && num < 100000000:
      unit = (num / 10000000).toFixed(2) + "千万";
      break;
    case num < 10000000 && num >= 1000:
      unit = (num / 10000).toFixed(2) + "万";
      break;
    case num < 1000:
      unit = num;
      break;
  }
  return metricton + unit;
};*/

const cache = {};
const timers = {};
/**
 * 股票推送
 * @param {*} id
 * @param {*} data
 * @param {*} callback
 */
export default function stockPush({ id, codes, source, callback }) {
  if (isWeb) return;

  cache[id] = source; //缓存
  setTimeout(() => {
    getDataFromClient(id, codes);
  }, 100);

  if (timers[id]) {
    clearInterval(timers[id]);
  } else {
    hub.on(REMOTE_DATA, callback);
  }
  // timers[id] = setInterval(() => {
  //   getDataFromClient(id, codes);
  // }, 2000);
}

/**
 * 服务器推送
 */
window.remoteCallback = function(data) {
  const arrs = data.split(";").filter((it) => it);
  const id = arrs[0].match(/\w+$/)[0];
  const value = arrs.filter((_, i) => i > 0).map((item) => item.split(","));
  //和旧数据进行合并
  const source = cache[id];
  const final = [];
  value.forEach((item, i) => {
    final.push({
      stockName: source[i].stockName,
      stockCode: source[i].stockCode,
      articleId: source[i].articleId,
      current: item[1],
      rise: formatNum(item[2]),
      toUp: formatNum(item[3]),
      netTurnover: formatNum(item[4] || 0),
    });
  });
  hub.emit(REMOTE_DATA, { id, value: final });
};

/**
 * 查询客户端股票和板块数据
 * @param {Array} codes - 股票代码或板块代码
 */
function getDataFromClient(id, codes) {
  const t = Date.now();
  codes = addPrefix(codes);
  codes = codes.map((it) => `"${it}"`).join(",");
  console.log(codes);
  window.prompt(
    "",
    `up://["user.info",${t}, {"type":"get_data", "data": {"reqid":"${id}", "stock": [ ${codes} ], "callback": "remoteCallback" } }]`
  );
}
